<?php
session_start();
include_once 'connect.php';

// 添加详细的错误日志
error_log("开始处理图片上传");

// 检查登录状态
if (!isset($_SESSION['loginadmin'])) {
    error_log("未登录状态下尝试上传图片");
    die(json_encode(['success' => 0, 'message' => '未登录']));
}

// 检查是否有文件上传
if (!isset($_FILES['editormd-image-file'])) {
    error_log("没有接收到上传文件");
    die(json_encode(['success' => 0, 'message' => '没有文件上传']));
}

// 设置允许的文件类型
$allowed = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
$file = $_FILES['editormd-image-file'];

error_log("接收到文件: " . $file['name'] . ", 类型: " . $file['type'] . ", 大小: " . $file['size'] . " 字节");

if (!in_array($file['type'], $allowed)) {
    error_log("不支持的文件类型: " . $file['type']);
    die(json_encode(['success' => 0, 'message' => '不支持的文件类型']));
}

// 创建上传目录
$upload_dir = '../uploads/images/' . date('Y/m/');
if (!file_exists($upload_dir)) {
    error_log("创建目录: " . $upload_dir);
    if (!mkdir($upload_dir, 0777, true)) {
        error_log("创建目录失败: " . $upload_dir . ", 错误: " . error_get_last()['message']);
        die(json_encode(['success' => 0, 'message' => '创建上传目录失败']));
    }
}

// 检查目录权限
if (!is_writable($upload_dir)) {
    error_log("目录不可写: " . $upload_dir);
    chmod($upload_dir, 0777);
    if (!is_writable($upload_dir)) {
        error_log("修改权限后仍不可写: " . $upload_dir);
        die(json_encode(['success' => 0, 'message' => '上传目录不可写']));
    }
}

// 生成唯一文件名
$extension = pathinfo($file['name'], PATHINFO_EXTENSION);
$filename = uniqid() . '.' . $extension;
$filepath = $upload_dir . $filename;

error_log("准备保存文件到: " . $filepath);

// 移动文件
if (move_uploaded_file($file['tmp_name'], $filepath)) {
    error_log("文件上传成功: " . $filepath);
    
    // 确保URL格式正确
    $fileurl = str_replace('../', '/', $filepath);
    error_log("文件URL: " . $fileurl);
    
    // 返回成功信息
    echo json_encode([
        'success' => 1,
        'message' => '上传成功',
        'url' => $fileurl
    ]);
} else {
    error_log("文件上传失败: " . error_get_last()['message']);
    echo json_encode([
        'success' => 0,
        'message' => '上传失败: ' . error_get_last()['message']
    ]);
} 